<script setup lang="ts">
import Taro, { getCurrentInstance, showToast, showLoading, hideLoading, navigateBack } from '@tarojs/taro';
import { onMounted, reactive, ref } from 'vue';
import { useAuthStore } from '@/store';
import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';
import { useNurseUser, useDict } from '@/service';
import { parseIdCard } from '@/utils';
import ren from '@/assets/img/ren.png';

const { edit } = useNurseUser();

const { getDict } = useDict();

const { nurseUser } = storeToRefs(useAuthStore());

const { nurseUserFamilyList } = nurseUser.value;

const {
    router: {
        params: { id }
    }
}: any = getCurrentInstance();

// definePageConfig({
//     navigationBarTitleText: id ? '设置被监护人信息' : '新增被监护人信息'
// });
Taro.setNavigationBarTitle({
    title: id ? '设置被监护人信息' : '新增被监护人信息'
});

const formData = ref<any>({
    name: '',
    sex: '',
    idcard: '',
    phone: '',
    isSelf: '',
    age: '',
    ageUnit: '岁',
    relation: '',
    relationName: '',
    record: '',
    status: '1',
    id: '',
    healthpic: '', // 电子健康码图片URL
    anfineid: '',
    avatar: '' // 头像
});

const editIndex = ref(nurseUserFamilyList?.findIndex(item => item.id == id));

/**
 * 将API返回的数据映射到formData格式
 */
function mapApiDataToFormData(apiData: any) {
    return {
        name: apiData.name || '',
        sex: apiData.sex || '',
        idcard: apiData.idcard || '',
        phone: apiData.phone || '',
        isSelf: apiData.isSelf || '',
        age: apiData.age || '',
        ageUnit: apiData.ageUnit || '岁',
        relation: apiData.relation || '',
        relationName: apiData.relationName || '',
        record: apiData.record || '',
        status: apiData.status || '1',
        avatar: apiData.avatar || '', // 头像
        id: apiData.id || '',
        healthpic: apiData.healthpic || apiData.healthpic || '',
        anfineid: apiData.anfineid || ''
    };
}

if (editIndex?.value !== undefined && id && nurseUserFamilyList) {
    formData.value = mapApiDataToFormData(nurseUserFamilyList[editIndex.value]);
}

onMounted(async () => {
    // 初始化时不需要加载数据，等用户选择医院后再加载部门数据
});

const ruleForm = ref<any>(null);


const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });

    if (id && editIndex.value !== undefined && nurseUserFamilyList) {
        nurseUserFamilyList[editIndex.value] = { ...formData.value };
    } else {
        nurseUserFamilyList?.push({
            ...formData.value,
            userId: nurseUser.value.id
        });
    }
    const data = { id: nurseUser.value.id, nurseUserFamilyList };

    const { error } = await edit(data);
    hideLoading();
    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
        setTimeout(() => {
            navigateBack();
        }, 1200);
        useGetAuthInfo();
    }
};

// 函数校验
const customValidator = (val: string) => {
    if (/^\d+$/.test(val)) {
        return Promise.resolve();
    }
    if (!val) return Promise.resolve();
    return Promise.reject('年龄必须输入整数数字');
};

const relationModule: any = reactive({
    show: false,
    columns: [],
    showRelation: () => {
        relationModule.show = !relationModule.show;
        // if (relationModule.show) {
        //     formData.value.relation = '';
        //     formData.value.relationName = '';
        // }
    },
    confirm: ({ selectedValue, selectedOptions }: any) => {
        formData.value.relation = selectedValue[0];
        formData.value.relationName = selectedOptions[0].text;
        relationModule.show = false;
    }
});

// 身份证号输入框失去焦点时解析
const onIdCardBlur = () => {
    if (formData.value.idcard) {
        const result = parseIdCard(formData.value.idcard);
        if (result.sex) {
            formData.value.sex = result.sex;
        }
        if (result.age) {
            formData.value.age = result.age;
            formData.value.ageUnit = result.ageUnit;
        }
    }
};

// 选择健康码图片
const choosehealthpicImage = () => {
    Taro.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            // 先显示临时图片
            formData.value.healthpic = tempFilePath;
            // 上传图片
            uploadrecord(tempFilePath);
        },
        fail: (err) => {
            // console.error('选择图片失败:', err);
            showToast({
                title: '选择图片失败',
                icon: 'none',
                duration: 2000
            });
        }
    });
};

// 上传健康码图片
function uploadrecord(filePath: string) {
    showLoading({ title: '上传中...' });
    Taro.uploadFile({
        url: 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage',
        filePath: filePath,
        name: 'file',
        formData: {},
        success: (uploadRes) => {
            hideLoading();
            // 上传成功，更新图片URL
            formData.value.healthpic = uploadRes.data;
            showToast({
                title: '上传成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
        },
        fail: (err) => {
            hideLoading();
            // console.error('上传失败:', err);
            showToast({
                title: '上传失败，请重试',
                icon: 'none',
                duration: 2000
            });
            // 上传失败，清空临时图片
            formData.value.healthpic = '';
        }
    });
}


// 头像选择处理
const onChooseAvatar = (e: any) => {
    formData.value.avatar = e.detail.avatarUrl;
    uploadAvatar(e.detail.avatarUrl);
}

// 上传头像
function uploadAvatar(filePath: string) {
    Taro.uploadFile({
        url: 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage',
        filePath: filePath,
        name: 'file',
        formData: {},
        success: (uploadRes) => {
            console.log("uploadRes", uploadRes);
            formData.value.avatar = uploadRes.data;
            showToast({
                title: '头像上传成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
        },
        fail: (err) => {
            showToast({
                title: '头像上传失败',
                icon: 'none',
                duration: 2000
            });
        }
    });
}

onMounted(async () => {
    const data = await getDict('nurse_relation');
    const relations = data?.map(item => {
        return { text: item.itemText, value: item.itemValue };
    });
    if (relations) relationModule.columns = [...relations];
});
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="id ? '设置被监护人信息' : '新增被监护人信息'" showLeft /> -->
        <view class="w-375px flex-col-center myf">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData" :label-width="200">
                    <!-- 头像选择区域 -->
                    <view class="w-full flex-center py-[40rpx] mb-[20rpx] bg-gray-50 rounded-[16rpx]">
                        <view class="flex-col-center">
                            <button 
                                class="relative mb-[16rpx]"
                                open-type="chooseAvatar" 
                                @chooseavatar="onChooseAvatar"
                            >
                                <image 
                                    class="w-[120rpx] h-[120rpx] rounded-[60rpx] border-[4rpx] border-white shadow-lg"
                                    :src="formData.avatar || ren" 
                                    mode="aspectFill"
                                ></image>
                                <view class="absolute bottom-0 right-0 w-[36rpx] h-[36rpx] bg-blue-500 rounded-[18rpx] flex-center shadow-md">
                                    <text class="text-white text-[24rpx] font-bold">+</text>
                                </view>
                            </button>
                           
                            <text class="text-[28rpx] text-gray-600">{{ '点击更换头像' }}</text>
                        </view>
                    </view>

                    <nut-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请填写姓名' }]">
                        <nut-input v-model="formData.name" placeholder="请输入姓名" type="text" :disabled="formData.isVerify == '1'" />
                    </nut-form-item>
                    <nut-form-item label="性别" prop="sex" :rules="[{ required: true, message: '请选择性别' }]">
                        <NutRadioGroup v-model="formData.sex" direction="horizontal">
                            <nut-radio label="1">男</nut-radio>
                            <nut-radio label="2">女</nut-radio>
                        </NutRadioGroup>
                    </nut-form-item>
                    <nut-form-item label="被监护人Anfineid" prop="anfineid" :rules="[{ required: false }]">
                        <nut-input v-model="formData.anfineid" placeholder="被监护人Anfineid" type="text" />
                    </nut-form-item>
                    <nut-form-item label="身份证号" prop="phone" :rules="[{ required: true, message: '请填写身份证号' }]">
                        <nut-input v-model="formData.idcard" placeholder="请填写身份证号" type="text" :disabled="formData.isVerify == '1'" @blur="onIdCardBlur" />
                    </nut-form-item>
                    <nut-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input v-model="formData.phone" placeholder="请输入联系电话" type="text" :disabled="formData.isVerify == '1'" />
                    </nut-form-item>
                    <nut-form-item label="病历号" prop="record" :rules="[{ required: false, message: '' }]">
                        <nut-input v-model="formData.record" placeholder="请输入病历号" type="text" />
                    </nut-form-item>
                    <nut-form-item label="电子健康码" prop="healthpic" :rules="[{ required: false, message: '' }]">
                        <view class="w-full flex flex-col">
                            <!-- 图片预览区域 -->
                            <view 
                                v-if="formData.healthpic" 
                                class="w-full mb-[20rpx] bg-gray-100 rounded-[16rpx] overflow-hidden"
                            >
                                <image 
                                    :src="formData.healthpic" 
                                    mode="aspectFit" 
                                    class="w-full max-h-[400rpx]"
                                />
                            </view>
                            <!-- 上传按钮 -->
                            <view 
                                class="w-full h-[120rpx] py-4 bg-gray-50 border-[2rpx] border-dashed border-gray-300 rounded-[16rpx] flex-center cursor-pointer"
                                @click="choosehealthpicImage"
                            >
                                <view class="flex-col-center">
                                    <view class="w-[48rpx] h-[48rpx] bg-blue-500 rounded-[24rpx] flex-center mb-[12rpx]">
                                        <text class="text-white text-[32rpx] font-bold">+</text>
                                    </view>
                                    <text class="text-[28rpx] text-gray-600">
                                        {{ formData.healthpic ? '重新上传' : '上传电子健康码' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </nut-form-item>

                    <nut-form-item label="关系" prop="relationName">
                        <nut-input v-model="formData.relationName" readonly placeholder="请选择关系" type="text"
                            @click="relationModule.showRelation" />
                        <nut-popup v-model:visible="relationModule.show" position="bottom">
                            <nut-picker :columns="relationModule.columns" title="选择关系"
                                @cancel="relationModule.show = false" @confirm="relationModule.confirm" />
                        </nut-popup>
                    </nut-form-item>
                    <nut-form-item class="w-full flex-center" label="年龄" prop="age" :rules="[
                        { required: false, message: '' },
                        { validator: customValidator, message: '' }
                    ]">
                        <view class="flex-center w-full">
                            <nut-input v-model="formData.age" placeholder="请输入年龄" type="text" />
                            <NutRadioGroup v-model="formData.ageUnit" class="!flex-center" direction="horizontal">
                                <nut-radio label="岁">岁</nut-radio>
                                <nut-radio label="月">月</nut-radio>
                                <nut-radio label="天">天</nut-radio>
                            </NutRadioGroup>
                        </view>
                    </nut-form-item>
                    <nut-form-item label="能否自理" prop="is_self">
                        <NutRadioGroup v-model="formData.isSelf" direction="horizontal">
                            <nut-radio label="1">正常自理</nut-radio>
                            <nut-radio label="2">不能自理</nut-radio>
                        </NutRadioGroup>
                    </nut-form-item>
                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
    </basic-layout>
</template>

<style lang="scss">
.myf {
    .nut-form-item__label {
        width: 222rpx;
    }
}
</style>